import { CertApi, CustomerApi } from '@/api';
import _ from 'lodash';
import Cert from '@/api/modules/Cert';
import AFileUploader from '@/components/AFileUploader/index.vue';
import AFileDownloader from '@/components/AFileDownloader/index.vue';
import ACompanySelector from '@/components/ACompanySelector/index.vue';
import CustomerCertInfoDialog from '@/views/CustomerDetail/components/CustomerCertInfoDialog.vue';
import { MappingTools, WorkflowMapping } from '@/mappings';
import AApprovalStatusTag from '@/components/AApprovalStatusTag/index.vue';

export default {
  name: 'CustomerDetail',
  components: {
    AApprovalStatusTag,
    CustomerCertInfoDialog,
    ACompanySelector,
    AFileDownloader,
    AFileUploader,
  },
  data() {
    return {
      certDialog: false,
      certSelection: {},
      customerInfo: {},
      customerInfoFormRule: {
        name: [
          {
            required: true,
            message: '客户姓名不能为空',
            trigger: 'blur',
          },
        ],
        IDcard: [
          {
            required: true,
            message: '身份证号不能为空',
            trigger: 'blur',
          },
          {
            min: 18,
            max: 18,
            message: '请输入正确的18位身份证号',
            trigger: 'blur',
          },
        ],
        sex: [
          {
            required: true,
            message: '请选择用户性别',
            trigger: 'blur',
          },
        ],
        birthday: [
          {
            required: true,
            message: '请填写用户生日',
            trigger: 'blur',
          },
        ],
      },
      attachmentList: [],
      certList: [],
    };
  },
  mounted() {
    if (this.$route.query.id) {
      this.fetchDetailData();
    }
  },
  computed: {
    // 将 attachmentList 分成每两个一组
    chunkedAttachmentList() {
      const chunks = [];
      for (let i = 0; i < this.attachmentList.length; i += 2) {
        chunks.push(this.attachmentList.slice(i, i + 2));
      }
      // return chunks;
      return [[{}]];
    },
    isNew() {
      return !this.$route.query.id;
    },
  },
  watch: {
    'customerInfo.IDcard': function (newval) {
      if (newval && newval.length === 18) {
        // 默认身份证号第7位到第14位是生日
        const year = newval.substring(6, 10);
        const month = newval.substring(11, 12);
        const day = newval.substring(13, 14);
        this.customerInfo.birthday = year + '-' + month + '-' + day;
      }
    },
  },
  methods: {
    matchTableFieldLabelStatus(row, column, cellValue) {
      return MappingTools.matchLabel(WorkflowMapping.Status, cellValue);
    },
    async fetchDetailData() {
      const response = await CustomerApi.detail(this.$route.query.id);
      this.customerInfo = response.result.client;
      this.certList = response.result.datalist.filter((o) => o.is_cert);
      this.attachmentList = response.result.datalist.filter((o) => !o.is_cert);
    },
    showAddCertDialog(row) {
      this.certSelection = row
        ? _.clone(row)
        : {
            type_id: '',
          };
      this.certDialog = true;
    },
    onDeleteCert(row) {
      const username = this.customerInfo.name;
      this.$confirm(
        `是否删除用户${username}的证书{${row.parent_name}-${row.type_name}}`
      )
        .then(() => {
          CertApi.deleteCert(row.data_id)
            .then(() => {
              this.$message.success('操作成功');
              this.fetchDetailData();
            })
            .catch((response) => {
              this.$message.error(response.msg);
            });
        })
        .catch(() => {});
    },
    onAddAttachmentItem() {
      this.$prompt('请输入附件名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(({ value }) => {
          this.attachmentList.push({ title: value });
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '取消输入'
          // });
        });
    },
    async onAttachmentUploadSuccess(index, filePath) {
      const client_id = this.$route.query.id;
      if (!client_id) {
        this.$message.warning('请先保存用户信息');
      } else {
        const attachmentItem = _.clone(this.attachmentList[index]);
        attachmentItem.file_path = filePath;
        try {
          if (attachmentItem.data_id) {
            await Cert.updateCert(client_id, attachmentItem);
          } else {
            await Cert.addCert(client_id, attachmentItem, 0);
          }
        } catch (e) {
          console.log(e);
          this.$message.error('保存附件失败: ' + JSON.stringify(e));
        }

        this.$message.success('操作成功');
        this.certDialog = false;
        this.fetchDetailData();
      }
    },
    onDeleteAttachment(row) {
      const username = this.customerInfo.name;
      this.$confirm(`是否删除用户${username}的附件{${row.title}}`)
        .then(() => {
          CertApi.deleteCert(row.data_id)
            .then(() => {
              this.$message.success('操作成功');
              this.fetchDetailData();
            })
            .catch((response) => {
              this.$message.error(response.msg);
            });
        })
        .catch(() => {});
    },
    onSaveCustomerInfo() {
      if (this.isSavingCustomerInfo) {
        this.$message.warning('请勿重复提交');
        return;
      }
      // console.log(this.customerInfo.status);
      // if (
      //   !!this.customerInfo.status &&
      //   MappingTools.valueInMapping(
      //     this.customerInfo.status,
      //     WorkflowMapping.Status.Pending,
      //     WorkflowMapping.Status.FirstPass
      //   )
      // ) {
      //   this.$message.warning('当前数据审核中，无法修改');
      //   return;
      // }

      this.$confirm(
        '此按钮仅保存基础信息、其他信息；证书信息和附件信息请在当前页面证书列表直接维护'
      )
        .then(() => {
          this.isSavingCustomerInfo = true;
          const clientId = this.$route.query.id;
          if (clientId) {
            this.onUpdateCustomerInfo(clientId);
          } else {
            this.onAddCustomerInfo();
          }
          this.isSavingCustomerInfo = false;
        })
        .catch(() => {
          this.isSavingCustomerInfo = false;
        });
    },
    onAddCustomerInfo() {
      CustomerApi.add(this.customerInfo)
        .then((response) => {
          this.$message.success('操作成功');
          this.$router.replace({
            path: '/customer/detail',
            query: { id: response.result.client_id },
          });
        })
        .catch((response) => {
          this.$message.error('操作失败:' + response.msg);
        });
    },
    onUpdateCustomerInfo(clientId) {
      CustomerApi.update(clientId, this.customerInfo)
        .then(() => {
          this.$message.success('操作成功');
          this.$router.back();
        })
        .catch((response) => {
          this.$message.error('操作失败:' + response.msg);
        });
    },
  },
};
